package com.sky.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.api.coupon.CouponFeignService;
import com.sky.api.product.ProductFeignService;
import com.sky.constant.WareConstant;
import com.sky.domain.WmsPurchase;
import com.sky.domain.WmsPurchaseDetail;
import com.sky.domain.WmsWareSku;
import com.sky.dto.SkuReductionDTO;
import com.sky.exception.BizException;
import com.sky.service.WmsPurchaseDetailService;
import com.sky.service.WmsPurchaseService;
import com.sky.mapper.WmsPurchaseMapper;
import com.sky.service.WmsWareSkuService;
import com.sky.utils.PageUtils;
import com.sky.utils.R;
import com.sky.utils.StringUtils;
import com.sky.vo.param.WmsPurchaseCompleteDetailsVO;
import com.sky.vo.param.WmsPurchaseCompleteVO;
import com.sky.vo.param.WmsPurchaseMergeVO;
import com.sky.vo.param.WmsPurchaseVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【wms_purchase(采购信息)】的数据库操作Service实现
* @createDate 2024-06-30 16:47:16
*/
@Service
public class WmsPurchaseServiceImpl extends ServiceImpl<WmsPurchaseMapper, WmsPurchase> implements WmsPurchaseService{

    @Resource
    private WmsPurchaseDetailService purchaseDetailService;
    @Resource
    private WmsWareSkuService wareSkuService;
    @Resource
    private ProductFeignService productFeignService;

    /**
     * 分页查询
     * @param vo
     * @return
     */
    @Override
    public PageUtils pageQuery(WmsPurchaseVO vo) {
        if (StringUtils.isNotEmpty(vo.getKey())){
            vo.setAssigneeName(vo.getKey());
        }
        PageUtils pageUtils = PageUtils.selectPage(baseMapper, vo, WmsPurchase.class);
        return pageUtils;
    }

    /**
     * 查询未领取的采购单
     *
     * @return
     */
    @Override
    public List<WmsPurchase> listUnReceivePurchase() {
        List<WmsPurchase> wmsPurchases = baseMapper.selectList(new LambdaQueryWrapper<WmsPurchase>().in(WmsPurchase::getStatus, 0, 1));
        return wmsPurchases;
    }

    /**
     * 合并采购单
     *
     * @param vo
     * @return
     */
    @Override
    public boolean merge(WmsPurchaseMergeVO vo) {
        Long purchaseId = vo.getPurchaseId();
        if (StringUtils.isEmpty(purchaseId)){
            // 新建采购单
            WmsPurchase wmsPurchase = new WmsPurchase();
            wmsPurchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(wmsPurchase);
            purchaseId = wmsPurchase.getId();
        }
        WmsPurchase wmsPurchase = this.getById(purchaseId);
        if (wmsPurchase.getStatus() != WareConstant.PurchaseStatusEnum.CREATED.getCode() && wmsPurchase.getStatus() != WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
            throw new BizException("采购单状态必须为新建或已分配");
        }
        if (StringUtils.isNotEmpty(vo.getItems())){
            // 添加关联关系
            List<Long> items = Arrays.asList(vo.getItems());
            for (Long item : items) {
                purchaseDetailService.update(null, new LambdaUpdateWrapper<WmsPurchaseDetail>()
                        .eq(WmsPurchaseDetail::getId, item)
                        .set(WmsPurchaseDetail::getPurchaseId, purchaseId)
                        .set(WmsPurchaseDetail::getStatus, WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()));
            }
        }

        this.update(null, new LambdaUpdateWrapper<WmsPurchase>()
                .eq(WmsPurchase::getId, purchaseId)
                .set(WmsPurchase::getStatus, WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()));

        return true;
    }

    /**
     * 领取采购单
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public boolean received(Long[] ids) {
        if (StringUtils.isNotEmpty(ids)) {
            for (Long id : ids) {
                WmsPurchase wmsPurchase = this.getById(id);
                if (wmsPurchase != null && wmsPurchase.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
                    // 更新采购单信息
                    this.update(null, new LambdaUpdateWrapper<WmsPurchase>()
                            .eq(WmsPurchase::getId, id)
                            .set(WmsPurchase::getStatus, WareConstant.PurchaseStatusEnum.RECEIVED.getCode()));
                    // 查询相关联的采购需求
                    List<WmsPurchaseDetail> wmsPurchaseDetails = purchaseDetailService.list(new LambdaQueryWrapper<WmsPurchaseDetail>()
                            .eq(WmsPurchaseDetail::getPurchaseId, id));
                    if (StringUtils.isNotEmpty(wmsPurchaseDetails)){
                        // 更新采购需求状态
                        for (WmsPurchaseDetail wmsPurchaseDetail : wmsPurchaseDetails) {
                            if (wmsPurchaseDetail.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()){
                                purchaseDetailService.update(null, new LambdaUpdateWrapper<WmsPurchaseDetail>()
                                        .eq(WmsPurchaseDetail::getId, wmsPurchaseDetail.getId())
                                        .set(WmsPurchaseDetail::getStatus, WareConstant.PurchaseDetailStatusEnum.BUYING.getCode()));
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * 完成采购单
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean complete(WmsPurchaseCompleteVO vo) {
        // 查询采购单信息
        WmsPurchase wmsPurchase = this.getById(vo.getPurchaseId());
        // 判断采购单状态
        if (wmsPurchase != null && wmsPurchase.getStatus() == WareConstant.PurchaseStatusEnum.RECEIVED.getCode()){
            boolean flag = true;
            if (StringUtils.isNotEmpty(vo.getItems())){
                // 更新采购需求状态
                for (WmsPurchaseCompleteDetailsVO item : vo.getItems()) {
                    if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                        flag = false;
                    }
                    WmsPurchaseDetail wmsPurchaseDetail = purchaseDetailService.getById(item.getItemId());
                    if (wmsPurchaseDetail.getStatus() == WareConstant.PurchaseDetailStatusEnum.BUYING.getCode()){
                        wmsPurchaseDetail.setStatus(item.getStatus());
                        purchaseDetailService.updateById(wmsPurchaseDetail);

                        // 查询商品库存
                        WmsWareSku wmsWareSku = wareSkuService.getOne(new LambdaQueryWrapper<WmsWareSku>()
                                .eq(WmsWareSku::getWareId, wmsPurchaseDetail.getWareId())
                                .eq(WmsWareSku::getSkuId, wmsPurchaseDetail.getSkuId()));
                        if (StringUtils.isNotEmpty(wmsWareSku)){
                            wmsWareSku.setStock(wmsWareSku.getStock() + wmsPurchaseDetail.getSkuNum());
                            wareSkuService.updateById(wmsWareSku);
                        } else {
                            WmsWareSku wareSku = new WmsWareSku();
                            wareSku.setWareId(wmsPurchaseDetail.getWareId());
                            // 调用远程接口查询商品信息
                            R r = productFeignService.getSkuInfoById(wmsPurchaseDetail.getSkuId());
                            if (r.getCode() == 0){
                                Map<String,Object> result = JSON.parseObject(r.getData().toString(),Map.class);
                                String skuName = result.get("skuName").toString();
                                wareSku.setSkuName(skuName);
                            } else {
                                throw new BizException("远程调用商品服务失败");
                            }
                            wareSku.setSkuId(wmsPurchaseDetail.getSkuId());
                            wareSku.setStock(wmsPurchaseDetail.getSkuNum());
                            wareSku.setStockLocked(0);
                            wareSkuService.save(wareSku);
                        }
                    }
                }
                // 更新采购单状态
                this.update(null, new LambdaUpdateWrapper<WmsPurchase>()
                        .eq(WmsPurchase::getId, vo.getPurchaseId())
                        .set(WmsPurchase::getStatus, flag ? WareConstant.PurchaseStatusEnum.FINISHED.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode()));
            }
        }
        return true;
    }
}




